<template>
    <div class="edit-profile">
        <h2 class="edit-title">修改信息</h2>

        <el-form :model="formData" :rules="rules" label-width="80px" class="edit-form">
            <!-- 昵称 -->
            <el-form-item label="昵称:" prop="username">
                <el-input v-model="formData.nickname" placeholder="请输入昵称" clearable />
            </el-form-item>

            <!-- 头像上传部分 -->
            <el-form-item label="头像:">
                <div class="avatar-uploader">
                    <el-upload class="avatar-upload" action="#" :show-file-list="false"
                        :before-upload="beforeAvatarUpload" :http-request="handleAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar-preview" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </div>
            </el-form-item>

            <!-- 性别 -->
            <el-form-item label="性别:" prop="gender">
                <el-radio-group v-model="formData.gander">
                    <el-radio label="女">女</el-radio>
                    <el-radio label="男">男</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 简介 -->
            <el-form-item label="简介:" prop="bio">
                <el-input v-model="formData.introduce" type="textarea" :rows="4" placeholder="请输入个人简介" show-word-limit
                    maxlength="300" />
            </el-form-item>

            <!-- 添加按钮组 -->
            <el-form-item>
                <div class="form-buttons">
                    <el-button type="primary" class="submit-btn" @click="handleSubmit">
                        提交
                    </el-button>
                    <el-button class="cancel-btn" @click="handleCancel">
                        取消
                    </el-button>
                </div>
            </el-form-item>

        </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeUnmount, watch, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { ElLoading } from 'element-plus'
import { PageConstant, getGandar, getGandarCode } from '@/common/Constant'
import { useUserStore } from '@/stores/userStores'
import { storeToRefs } from 'pinia'
import { ParameterException } from '@/exception/ParameterException'
import { BusinessException } from '@/exception/BusinessException'
import type { User } from '@/typedefined/User'


const router = useRouter()
const userStore = useUserStore() // 添加这行
const { userInfo } = storeToRefs(userStore);
const { uploadAvatar, requestUpdateUserInfo } = userStore;

const imageUrl = ref('') // 用于存储预览图片的 URL

// 头像上传前的验证
const beforeAvatarUpload = (file: File): void => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === "image/jpg"
    const isLt2M = file.size / 1024 / 1024 < 5
    if (!isJpgOrPng) {
        throw new ParameterException("头像只能是 JPG 或 PNG 格式!");
    }
    if (!isLt2M) {
        throw new ParameterException("头像大小不能超过 2MB!");
    }
}

// 处理头像上传
const handleAvatarUpload = async (options: any) => {
    // 获取file对象
    const file = options.file
    const oldUrl = imageUrl.value;
    // 创建本地预览URL
    imageUrl.value = URL.createObjectURL(file)

    // 添加 loading 效果
    const loading = ElLoading.service({
        lock: true,
        text: '头像上传中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
        // 先上传文件获取URL
        const res_imageUrl = await uploadAvatar(file);
        if (!res_imageUrl) {
            throw new BusinessException('头像上传失败');
        }
        imageUrl.value = res_imageUrl
        formData.avatar = res_imageUrl
        userInfo.value.avatar = res_imageUrl
        ElMessage.success('头像上传成功')
    } catch (error) {
        console.error('上传出错:', error)
        ElMessage.error('上传过程中发生错误');
        imageUrl.value = oldUrl;
    } finally {
        // 无论成功与否都关闭 loading
        loading.close()
    }

    return false
}

// 在组件卸载时清理 URL
onBeforeUnmount(() => {
    if (imageUrl.value) {
        URL.revokeObjectURL(imageUrl.value)
    }
})

// 表单的初始化数据
const formData = reactive({
    nickname: '',
    avatar: '',
    gander: "男",
    introduce: ''
})

// 组件加载完毕时调用的钩子函数
onMounted(() => {
    formData.nickname = userInfo.value.nickname
    formData.gander = getGandar(userInfo.value.gander);
    formData.introduce = userInfo.value.introduce
    imageUrl.value = userInfo.value.avatar
});


watch(userInfo, (newVal) => {
    if (newVal.nickname) {
        formData.nickname = newVal.nickname
    }
    if (newVal.gander) {
        formData.gander = getGandar(newVal.gander)
    }
    if (newVal.introduce) {
        formData.introduce = newVal.introduce
    }
    if (newVal.avatar) {
        imageUrl.value = newVal.avatar
    }
});

// 表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    bio: [
        { max: 300, message: '简介不能超过300字', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ]
}


// 修改提交处理函数
const handleSubmit = async () => {
    const updateData = {
        nickname: formData.nickname,
        gander: getGandarCode(formData.gander),
        introduce: formData.introduce
    }

    const loading = ElLoading.service({
        lock: true,
        text: '保存中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
        await requestUpdateUserInfo(updateData as User);
        ElMessage.success('保存成功')
        router.replace('/profile')
    } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败，请重试')
    } finally {
        loading.close()
    }
}

// 取消编辑
const handleCancel = () => {
    // 跳转到个人信息页面
    router.replace(PageConstant.ProfilePage);
}

</script>

<style scoped>
.edit-profile {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.edit-title {
    margin-bottom: 30px;
    font-size: 20px;
    color: #303133;
}

.avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
}

.avatar-preview {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}


:deep(.el-textarea__inner) {
    font-family: inherit;
}

.form-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
}

.submit-btn {
    width: 120px;
    height: 40px;
    font-size: 16px;
}

.cancel-btn {
    width: 120px;
    height: 40px;
    font-size: 16px;
}

/* 覆盖 Element Plus 的默认样式 */
:deep(.el-button--primary) {
    background-color: #409EFF;
    border-color: #409EFF;
}

:deep(.el-button--default) {
    background-color: white;
    border-color: #dcdfe6;
    color: #606266;
}
</style>